package com.wnxy.pawnbackgroundsystem.commons;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.InputStream;
@Configuration
public class OssTemplate {
    //我们创建bucket之后指定的地域节点的域名
    private String endPoint = "oss-cn-chengdu.aliyuncs.com";

    //账号的id标识
    private String accessKeyId = "LTAI5t5nyDnpLq3PU72zEGvG";

    //账号的key标识
    private String accessKeySecret = "WnDreerJ6YwA3WookN2DLLwMZyBxZV";

    //是OSSapi提供用来构建客户端对象的建造器对象
    private OSSClientBuilder oSSClientBuilder = new OSSClientBuilder();

    /**
     *把本地的文件上传的OSS
     *bucketName：空间名
     *fileName： 文件名
     *file： 文件
     */
    public String uploadFile(String bucketName, String fileName, File file) {
        OSS ossClient = null;
        try {
            //通过建造器对象创建客户端对象
            ossClient = oSSClientBuilder.build(endPoint, accessKeyId,accessKeySecret);
            //调用上传方法
            ossClient.putObject(bucketName,fileName,file);
            //组件该文件的访问地址
            return "http://" + bucketName + "." + endPoint + "/" + fileName;
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
    }

    //该方法唯一不一样就是代表文件的参数是流
    public String uploadFile(String bucketName, String fileName, InputStream file) {
        OSS ossClient = null;
        try {
            ossClient = oSSClientBuilder.build(endPoint, accessKeyId,accessKeySecret);
            ossClient.putObject(bucketName,fileName,file);
            return "http://" + bucketName + "." + endPoint + "/" + fileName;
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
    }

    //删除文件
    public boolean deleteFile(String bucketName,String fileName) {
        OSS ossClient = null;
        try {
            ossClient = oSSClientBuilder.build(endPoint, accessKeyId,accessKeySecret);
            ossClient.deleteObject(bucketName, fileName);
            return true;
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
    }
}
